package com.hz.foodstalls.controller;

import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;

import com.hz.foodstalls.exception.IncorrectCaptchaException;
import com.hz.foodstalls.model.Admin;
import com.hz.foodstalls.model.ComplaintAdvice;
import com.hz.foodstalls.model.Resource;
import com.hz.foodstalls.services.DemoService;
import com.jfinal.core.ActionKey;
import com.jfinal.ext.plugin.shiro.JdbcShiroPlugin;
import com.jfinal.ext.plugin.shiro.ShiroMethod;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.log.Log;
import com.jfinal.plugin.ehcache.CacheKit;

/**
 * Created by toucheserver on 2016/2/16.
 */
@ControllerBind(controllerKey = "/", viewPath = "/WEB-INF/views/")
public class LoginController extends BaseController {
    // private static Logger log =
    // LoggerFactory.getLogger(LoginController.class);
    Log log = Log.getLog(LoginController.class);

    public void index() {
        if (ShiroMethod.authenticated()) {
            String username = getSessionAttr("username");
            Admin admin = Admin.dao.findFirst("select * from admin where username=?", username);
            String areaId = admin.getAreaId();
            int num = 0;
            if (areaId.isEmpty()) {
                List list = ComplaintAdvice.dao.find("select * from complaint_advice ");
                int total = list.size();
                List list2 = ComplaintAdvice.dao.find("select * from complaint_advice where status = 1 or status = 2");
                int total2 = list2.size();
                int total3 = total - total2;
                List list4 = ComplaintAdvice.dao
                        .find("select * from complaint_advice where finish_time  is NULL and  work_day  < CURDATE()");
                int total4 = list4.size();
                setAttr("total", total);
                setAttr("total2", total2);
                setAttr("total3", total3);
                setAttr("total4", total4);

            } else {
                List list = ComplaintAdvice.dao.find("select * from complaint_advice where areaId in (" + areaId + ")");
                int total = list.size();
                List list2 = ComplaintAdvice.dao
                        .find("select * from complaint_advice where areaId in (" + areaId + ") and status = 1 ");
                int total2 = list2.size();
                int total3 = total - total2;

                List list4 = ComplaintAdvice.dao
                        .find("select * from complaint_advice where finish_time  is NULL and  work_day  < CURDATE() and areaId in ("
                                + areaId + ") ");
                int total4 = list4.size();

                setAttr("total", total);
                setAttr("total2", total2);
                setAttr("total3", total3);
                setAttr("total4", total4);
            }
            setAttr("treeviews", getSessionAttr("treeviews"));
            render("index.html");
        } else

        {
            redirect("/admin/login");
        }

    }

    public void captcha() {
        renderCaptcha();
    }

    @ActionKey("/admin/login")
    public void login() {
        render("login.html");
    }

    @ActionKey("/admin/signout")
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        redirect("/admin/login");
    }

    @ActionKey("/admin/singin")
    public void signin() {
        Subject subject = SecurityUtils.getSubject();
        String username = getPara("username", "");
        String password = getPara("password", "");
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            doCaptchaValidate("captcha");
            subject.login(token);
        } catch (IncorrectCaptchaException ice) {
            token.clear();
            setSessionAttr("shiroLoginFailure", ice.getClass().getSimpleName());
        } catch (UnknownAccountException ue) {
            token.clear();
            setSessionAttr("shiroLoginFailure", ue.getClass().getSimpleName());
        } catch (IncorrectCredentialsException ie) {
            token.clear();
            setSessionAttr("shiroLoginFailure", ie.getClass().getSimpleName());
        } catch (LockedAccountException le) {
            token.clear();
            setSessionAttr("shiroLoginFailure", le.getClass().getSimpleName());
        } catch (RuntimeException re) {
            token.clear();
            setSessionAttr("shiroLoginFailure", re.getClass().getSimpleName());
        }
        // 登录成功后
        if (ShiroMethod.authenticated()) {
            setSessionAttr("username", username);
            JdbcShiroPlugin.setMenu(this);// 登陆设置动态菜单缓存
            // 跳转回上一次访问的页面，需要配合shiro.ini里面的authc过滤器
            SavedRequest request = WebUtils.getSavedRequest(getRequest());
            String ctx = WebUtils.getContextPath(getRequest());
            if (null != request && request.getMethod().equalsIgnoreCase("GET")
                    && StringUtils.isNotBlank(request.getRequestUrl().replace(ctx, "")))
                redirect(request.getRequestUrl().replace(ctx, ""));
            else
                redirect("/");
        } else {
            redirect("/admin/login");
        }
    }

    public void servicetx() {
        boolean ret = new DemoService().service.usersave();
        renderText(ret + "");
    }

    public void saveuser() {
        Admin.dao.findFirst("select * from admin").set("loginFailureCount", 1).update();

        // new Resource().set("id", UUID.randomUUID().toString().replace("-",
        // "")).save();
        renderText("test successed." + CacheKit.get("index", "test"));
    }

    public void usersave() {
        Admin.dao.findFirst("select * from admin").set("loginFailureCount", 2).update();
        CacheKit.put("index", "test", "value");
        new Resource().set("id", UUID.randomUUID().toString().replace("-", "")).set("isSystem", 0).set("name", "test")
                .set("orderList", "1").set("value", "admin1").save();
        renderText("test successed." + CacheKit.get("index", "test"));
    }
}
